package com.creditease.mobile.rss.provider;

import java.io.File;
import java.io.FileNotFoundException;

import com.creditease.mobile.rss.RssConst;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;

public class ImageProvider extends ContentProvider {

	private static final String IMAGE_PREFIX = "content://com.creditease.image/";

	public static String match(String uri) {

		if ((uri == null) || (!uri.startsWith(IMAGE_PREFIX))) {
			return null;
		}

		return Uri.decode(uri.substring(IMAGE_PREFIX.length()));
	}

	@Override
	public boolean onCreate() {

		return true;
	}

	@Override
	public Cursor query(Uri uri,
						String[] projection,
						String selection,
						String[] selectionArgs,
						String sortOrder) {
		throw new UnsupportedOperationException("Not supported by this provider");
	}

	@Override
	public String getType(Uri uri) {
		throw new UnsupportedOperationException("Not supported by this provider");
	}

	/*
	 * 就是做一次映射，返回uri指定的文件的文件描述符
	 */
	@Override
	public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
		String path = uri.getPath();
		String tmp = match(path);
		if (tmp != null) {
			File file = new File(getContext().getExternalFilesDir(RssConst.APP_NAME), path);
			if (file.exists()) {
				return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
			}
		}
		throw new FileNotFoundException(path);
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		throw new UnsupportedOperationException("Not supported by this provider");
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		throw new UnsupportedOperationException("Not supported by this provider");
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		throw new UnsupportedOperationException("Not supported by this provider");
	}
}